import { useEffect, useRef } from 'react';
import * as THREE from 'three';
import styles from './index.module.less';
// 引入轨道控制器扩展库OrbitControls.js
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';


const Test = () => {
  const canvasRef = useRef();

  const init = () => {
    // 创建3D场景对象Scene
    const scene = new THREE.Scene();

    const renderer = new THREE.WebGLRenderer({
      canvas: canvasRef.current,
      antialias: true,
      alpha: true
    });

    renderer.setSize(window.innerWidth, window.innerHeight);

    // 设置几何体长宽高，也就是x、y、z三个方向的尺寸
    //对比三个参数分别对应xyz轴哪个方向
    const geometry = new THREE.BoxGeometry(100, 60, 20);
    const texture = new THREE.TextureLoader().load("https://jr-prod-pim-products.oss-cn-beijing.aliyuncs.com/i/9437af46-1820-432b-b882-a1455d4d1be9/wallfloor.jpg");
    //创建一个材质对象Material
    const material = new THREE.MeshBasicMaterial({
      map: texture
      // color: 0xff0000,//0xff0000设置材质颜色为红色
    }); 

    const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
    //设置网格模型在三维空间中的位置坐标，默认是坐标原点
    mesh.position.set(0,0,0);

    // 添加
    scene.add(mesh);

    // 30:视场角度, width / height:Canvas画布宽高比, 1:近裁截面, 3000：远裁截面
    const camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 3000);
    
    camera.position.set(-500, 0, 0);
    camera.lookAt(0, 0, 0);

    renderer.render(scene, camera);

    const controls = new OrbitControls(camera, renderer.domElement);
    // 如果OrbitControls改变了相机参数，重新调用渲染器渲染三维场景
    controls.addEventListener('change', function () {
        renderer.render(scene, camera); //执行渲染操作
    });//监听鼠标、键盘事件
  }

  useEffect(() => {
    init();
  }, []);

  return (
    <div className={styles.container}>
      <canvas className={styles.webgl} ref={canvasRef}></canvas>
    </div>
  );
};

export default Test;